// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const _data = JSON.parse(JSON.stringify(event))
  const result = {}
  const bookDb = cloud.database().collection('books').where({
    bookId: parseInt(_data.bookId),
  })

  const bookData = await bookDb.get()
  const book = bookData.data[0]
  delete book._id
  book.comments.splice(_data.index, 1)
  result.result1 = await bookDb.update({
    data: book
  })

  // 找到对应评论获取所有者id
  const commentsDb = cloud.database().collection('comments')
  const commentData = await commentsDb.where({
    commentId: _data.commentId
  }).get()
  const comment = commentData.data[0]
  const _id = comment.id
  
  result.result2 = await cloud.database().collection('comments').where({
    commentId: parseInt(_data.commentId)
  }).remove()

  // 删除对应用户中的评论
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    _id
  }).get()
  const user = userData.data[0]
  delete user._id
  const newComments = user.comments.filter(item => _data.commentId !== item.commentId)
  user.comments = newComments
  result.result3 = await usersDb.where({
    _id
  }).update({
    data: user
  })
  return result
}
